package com.pay.controller.api.frontend;

import com.pay.common.JsonResult;
import com.pay.common.ProcessAPI;
import com.pay.common.enums.ResultCode;
import com.pay.controller.Routes;
import com.pay.domain.entity.City;
import com.pay.lifecycle.repository.CityRepository;
import com.pay.lifecycle.repository.ProvinceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *
 * @author Evan
 * @date 2018/2/4
 */
@Controller
public class LocationCtroller {
    private Logger logger = LoggerFactory.getLogger(LocationCtroller.class);

    @Autowired
    private CityRepository cityRepository;

    @Autowired
    private ProvinceRepository provinceRepository;


    /**
     * 获取所有省份列表
     * @param request
     * @return
     */
    @RequestMapping(value = Routes.GET_PROVINCE_LIST, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getProvinceList(HttpServletRequest request){
        ProcessAPI api = (result, validate) -> result.result = provinceRepository.findAll();
        return api.process(request);
    }

    /**
     * 根据省编码查询城市
     * @param request
     * @param provinceCode
     * @return
     */
    @RequestMapping(value = Routes.GET_CITY_LIST_BY_PROVINCE_CODE, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getCityListByProvinceCode(HttpServletRequest request,Integer provinceCode){
        ProcessAPI api = (result, validate) -> {
            logger.info("getCityListByProvinceCode provinceCode ={}",provinceCode);
            validate.check("provinceCode",provinceCode);
            List<City> cityList = cityRepository.findByProvinceCode(provinceCode);
            if (cityList.isEmpty()){
                result.resultCode = ResultCode.NO_DATA.getCode();
                result.msg = ResultCode.NO_DATA.getMsg();
                return;
            }
            result.result = cityList;
            result.size = Long.valueOf(cityList.size());

        };
        return api.process(request);
    }


}
